//
//  InChannelViewController.m
//  Inner  Voice
//
//  Created by Martin.Wang on 16/2/29.
//  Copyright © 2016年 徐海宇. All rights reserved.
//

#import "InChannelViewController.h"

#import "InChannelCollectionViewCell.h"

#import "InChannelCollectionReusableView.h"

#import "InChannelSoundsViewController.h"

#import <AFNetworking.h>

#import <MJRefresh.h>

#import "AppDelegate.h"

@interface InChannelViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@property (strong, nonatomic) NSMutableArray *channelArray;

@property (weak, nonatomic)InChannelCollectionReusableView *channelReusabelView;

@property (nonatomic, assign) int page;

@end

static NSString *kcellIdentifier = @"channelCellID";

static NSString *kheaderIdentifier = @"classReusableView";

@implementation InChannelViewController


- (void)viewDidLoad {
    
    [super viewDidLoad];
//    myCollectionView代理
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    
    //通过Nib生成cell，然后注册 Nib的view需要继承 UICollectionViewCell
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"InChannelCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kcellIdentifier];
    
    //注册headerView Nib的view需要继承UICollectionReusableView
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"InChannelCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kheaderIdentifier];
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    // 上拉刷新
    self.myCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.channelReusabelView.page++;
        
        
        __weak typeof (self) tempSelf = self;
        
        if (self.channelReusabelView.hotBtn.selected) {
            
            [tempSelf xiahomeHotChannelRecommendWithPage:tempSelf.channelReusabelView.page];
            
        }else{
        
            [tempSelf xiahomeNewChannelWithPage:tempSelf.channelReusabelView.page];
            
        }
        
    }];
}else {
        [self showAlertView:@"当前网络不可用"];
    }
    // Do any additional setup after loading the view from its nib.
}
#pragma mark - 封装UIAlertView方法，直接调用就可以显示提示
-(void)showAlertView:(NSString *)string {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    
}

- (void)xiahomeNewChannelWithPage:(int)page{
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    NSString *url = [NSString stringWithFormat:@"http://1.wangtest11.applinzi.com/home/Banner/backchannelNew?page=%d",page];
    
    
    AFHTTPSessionManager *httpSession1 = [AFHTTPSessionManager manager];
    
    
    [httpSession1 GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSArray *channels = dic[@"data"];
        
        if (!channels) {
            
            [self.myCollectionView.mj_footer endRefreshing];
            
            self.page--;
            
            return ;
            
        }
        
        int a = (int)[channels count];
        
        for (int b = 0; b < a; b++) {
            
            [self.channelArray addObject:channels[b]];
            
        }
        
        [self.myCollectionView reloadData];
        
        [self.myCollectionView.mj_footer endRefreshing];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"频道 ERROR %@",error);
        
    }];
    }else {
        [self showAlertView:@"当前网络不可用"];
    }
}

- (void)xiahomeHotChannelRecommendWithPage:(int)page{
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    NSString *url = [NSString stringWithFormat:@"http://1.wangtest11.applinzi.com/home/Banner/backchannelHot?page=%d",page];
    
    
    AFHTTPSessionManager *httpSession1 = [AFHTTPSessionManager manager];
    
    
    
    [httpSession1 GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSArray *channels = dic[@"data"];
        
        if (!channels) {
            
            [self.myCollectionView.mj_footer endRefreshing];
            
            self.page--;
            
            return ;
            
        }
        
        int a = (int)[channels count];
        
        for (int b = 0; b < a; b++) {
            
            [self.channelArray addObject:channels[b]];
            
        }
        
        
        [self.myCollectionView reloadData];
        
        [self.myCollectionView.mj_footer endRefreshing];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"频道 ERROR %@",error);
        
    }];
}else {
    [self showAlertView:@"当前网络不可用"];
}

}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    
    
    self.channelReusabelView =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:kheaderIdentifier   forIndexPath:indexPath];
    
    __weak typeof (self) tempSelf = self;
    
    tempSelf.channelReusabelView.hotChannel = ^(int a){

        [self.channelArray removeAllObjects];
   
        [self.myCollectionView reloadData];
        
        [tempSelf xiahomeHotChannelRecommendWithPage:a];
        
        
    };
    
    tempSelf.channelReusabelView.newChannel = ^(int a){
        
        [self.channelArray removeAllObjects];

        [self.myCollectionView reloadData];
        
        [tempSelf xiahomeNewChannelWithPage:a];
        
        
    };
    
    
    return self.channelReusabelView;
}

#pragma mark -CollectionView datasource
//section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.channelArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //重用cell
    InChannelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcellIdentifier forIndexPath:indexPath];
    
    NSDictionary *channel = self.channelArray[indexPath.row];
    
    
    [cell loadImageWithStr:channel[@"pic_200"]];

    
    cell.channelName.text = channel[@"name"];
    
    
    
    return cell;
    
}

//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width/2.2, self.view.frame.size.height/8);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, self.view.frame.size.width/50, 10, self.view.frame.size.width/50);

}
//返回头headerView的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={self.view.frame.size.width,self.view.frame.size.height/6};
    return size;
}

//选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    InChannelSoundsViewController *controller = [[InChannelSoundsViewController alloc] init];
    
    __weak typeof (self) temp = self;
    
    NSDictionary *channel = self.channelArray[indexPath.row];
    
    controller.dic = channel;
    
    if (!channel) {
        return;
    }
    NSLog(@"1231231231231233121212121%@",channel);
    //push用在UINavigationController下得语句
    [temp.navigationController pushViewController:controller animated:YES];
    
    
}

//取消选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor whiteColor]];
}

//每个item之间的间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//    return 100;
//}

- (NSMutableArray*)channelArray{

    if (_channelArray == nil) {
        
        _channelArray = [NSMutableArray array];
        
    }
    
    return _channelArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
